package com.tcheung.web.controller;

import com.tcheung.common.entity.QueryResult;
import com.tcheung.service.QueryService;
import com.tcheung.web.spring.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;

/**
 * IndexController
 *
 * @author: zhangteng
 * @time: 2014/12/13 11:28
 */
@Controller
@RequestMapping("")
public class IndexController extends AbstractController {

    @Autowired
    private QueryService queryService;

    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    public String index(Model model) {
        return "redirect:/search";
    }

    @RequestMapping(value = "search", method = RequestMethod.GET)
    public String toSearch() {
        return "index";
    }

    @RequestMapping(value = "search", method = RequestMethod.POST)
    public String search(@RequestParam("queryContent") String queryContent,
                         Model model) {
        Date startTime = new Date();
        List<QueryResult> queryResultList = queryService.query(queryContent);
        Date endTime = new Date();
        model.addAttribute("queryResultList", queryResultList);
        model.addAttribute("queryContent", queryContent);
        model.addAttribute("time", endTime.getTime() - startTime.getTime());
        return "result";
    }

    @RequestMapping(value = "doc/{doc}", method = RequestMethod.GET)
    public String view(@PathVariable String doc,
                       @RequestParam("queryContent") String queryContent,
                       Model model) {
        model.addAttribute("swfFileName", doc+ ".swf");
        model.addAttribute("queryContent", queryContent);
        return "view";
    }
}
